package com.qingzhu.component.lock.common.config.ognl;

import com.qingzhu.component.lock.common.constant.AutoConfig;
import com.qingzhu.component.lock.common.util.BaseUtil;
import ognl.*;

/**
 * ognl对象生成器
 * @author xiangjz
 * @version 1.0
 * @date 2021/6/9 13:59
 */
public class OgnlContextGenerator {

    /**
     * 生成一个ognl上下文对象
     * @param root
     * @return
     */
    public static OgnlContext generate(Object root) {
        OgnlContext context = (OgnlContext) Ognl.createDefaultContext(root,
                new DefaultMemberAccess(true), new DefaultClassResolver(), new DefaultTypeConverter());
        context.put("root", root);
        return context;
    }

    public static String getValue(OgnlContext context, String key) {
        try {
            return BaseUtil.retStr(Ognl.getValue("#root." + key, context, context.getRoot()));
        } catch (OgnlException e) {
            e.printStackTrace();
            return null;
        }
    }
}
